﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Xml.Dom;
using Windows.Foundation;
using Windows.UI;
using Windows.UI.Popups;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media;
using Windows8Accelerator.Core.Xaml.Controls;
using Windows8Accelerator.Core.Xaml.Helpers;

namespace Windows8Accelerator.Core.Xaml.ViewModels
{
    public class SuperSplashPageViewModel : ViewModelBase
    {
        public SuperSplashPageViewModel(Rect splashScreenImageLocation, object parameter, Func<SuperSplashPageViewModel, Task> extendedSplashLoadingFunction, Type defaultStartPageType)
        {
            SplashScreenImageLocation = splashScreenImageLocation;
            Parameter = parameter;
            AsyncLoadingFunction = extendedSplashLoadingFunction;
            NavigateToPageType = defaultStartPageType;
        }

        public object Parameter { get; set; }

        public Rect SplashScreenImageLocation { get; private set; }

        public Func<SuperSplashPageViewModel, Task> AsyncLoadingFunction { get; set; }

        public Type NavigateToPageType { get; set; }

        private string _ErrorMessage;
        public string ErrorMessage
        {
            get { return _ErrorMessage; }
            set
            {
                _ErrorMessage = value;
                NavigateToPageType = null;
            }
        }

        public async Task PreLoadAsync()
        {
            if (TextStyle == null)
            {
                var resourceDictionary = new ResourceDictionary();
                resourceDictionary.Source = new Uri("ms-appx:///W8A.C.X/Themes/Generic.xaml");
                TextStyle = resourceDictionary["SplashScreenTextStyle"] as Style;
            }
            
            var installedFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
            var xmlDocument = await XmlDocument.LoadFromFileAsync(await installedFolder.GetFileAsync("AppxManifest.xml"));
            //var namespaceManager = new XmlNamespaceManager(xmlDocument.OwnerDocument.);
            //namespaceManager.AddNamespace("myprefix", "http://www.w3.org/1999/xhtml"); 
            //TODO: Fix namespace issue
            var backgroundColorNode = xmlDocument.SelectSingleNode("//*[local-name()='SplashScreen']/@BackgroundColor");
            if (backgroundColorNode != null)
            {
                var backgroundColorString = backgroundColorNode.NodeValue as string;
                Background = new SolidColorBrush(ColorHelperEx.StringToColor(backgroundColorString));
            }

            var imageNode = xmlDocument.SelectSingleNode("//*[local-name()='SplashScreen']/@Image");
            if (imageNode != null)
            {
                var imagePath = imageNode.NodeValue as string;
                ImagePath = "ms-appx:///" + imagePath.Replace("\\", "/");
            }
            ImageMargin = new Thickness(0, SplashScreenImageLocation.Top, 0, 0);
            ContentHorizontalAlignment = HorizontalAlignment.Left;
            ContentMargin = new Thickness(SplashScreenImageLocation.Left, 0, 0, 0);
        }
       
        private Style _TextStyle;
        public Style TextStyle
        {
            get { return this._TextStyle; }
            set { this.SetProperty(ref this._TextStyle, value); }
        }

        private Brush _Background;
        public Brush Background
        {
            get { return this._Background; }
            set { this.SetProperty(ref this._Background, value); }
        }

        private string _ImagePath;
        public string ImagePath
        {
            get { return this._ImagePath; }
            set { this.SetProperty(ref this._ImagePath, value); }
        }

        private string _Text;
        public string Text
        {
            get { return this._Text; }
            set { this.SetProperty(ref this._Text, value); }
        }

        private Thickness _ImageMargin;
        public Thickness ImageMargin
        {
            get { return this._ImageMargin; }
            set { this.SetProperty(ref this._ImageMargin, value); }
        }

        private Thickness _ContentMargin;
        public Thickness ContentMargin
        {
            get { return this._ContentMargin; }
            set { this.SetProperty(ref this._ContentMargin, value); }
        }

        private HorizontalAlignment _ContentHorizontalAlignment;
        public HorizontalAlignment ContentHorizontalAlignment
        {
            get { return this._ContentHorizontalAlignment; }
            set { this.SetProperty(ref this._ContentHorizontalAlignment, value); }
        }

        private VerticalAlignment _ContentVerticalAlignment;
        public VerticalAlignment ContentVerticalAlignment
        {
            get { return this._ContentVerticalAlignment; }
            set { this.SetProperty(ref this._ContentVerticalAlignment, value); }
        }

        private Stretch _ImageStretch;
        public Stretch ImageStretch
        {
            get { return this._ImageStretch; }
            set { this.SetProperty(ref this._ImageStretch, value); }
        }


        public async Task LoadAsync()
        {
            try
            {
                AsyncLoadingFunction(this).ContinueWith((task) => {
                    if (task.IsCompleted)
                    {
                        AppHelperBase.Instance.RunOnUIAsync(async () =>
                        {
                            if (NavigateToPageType == null)
                            {
                                var errorMessage = new MessageDialog(ErrorMessage);
                                await errorMessage.ShowAsync();
                                Application.Current.Exit();
                            }
                            else
                            {
                                AppHelper.Frame.Navigate(NavigateToPageType, Parameter);
                            }
                        });
                    }
                    else
                    {
                        Application.Current.Exit();
                    }
                });
            }
            catch
            {
            }
        }
        

        public void OnWindowSizeChanged()
        {
            ContentMargin = new Thickness();
            ImageMargin = new Thickness();
            ContentHorizontalAlignment = HorizontalAlignment.Stretch;
            ContentVerticalAlignment = VerticalAlignment.Center;
            if (ApplicationView.Value == ApplicationViewState.Snapped)
                ImageStretch = Stretch.Uniform;
            else
                ImageStretch = Stretch.None;
        }
    }

}
